package com.autumn.sms.service.services.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.autumn.redis.AutumnRedisTemplate;
import com.autumn.sms.service.consts.RedisKeyConsts;
import com.autumn.sms.service.services.ICacheService;
import com.autumn.sms.service.vo.SendTemplateValue;
import com.autumn.util.function.FunctionOneResult;

/**
 * 缓存服务实现
 * 
 * @author 老码农
 *
 *         2018-01-12 13:43:17
 */
@Service
public class CacheServiceImpl implements ICacheService {

	@Autowired
	private AutumnRedisTemplate redisTemplate;

	/**
	 * 获取发送模板键
	 * 
	 * @param serviceId
	 *            服务id
	 * @return
	 *
	 */
	private String getSendTemplateKey(String serviceId) {
		return RedisKeyConsts.SERVICE_SEND_TEMPLATE_KEY_PREFIX + serviceId.toUpperCase();
	}

	@Override
	public SendTemplateValue getSendTemplate(String serviceId) {
		String key = getSendTemplateKey(serviceId);
		return redisTemplate.get(key, SendTemplateValue.class);
	}

	@Override
	public SendTemplateValue getSendTemplate(String serviceId, FunctionOneResult<String, SendTemplateValue> fun) {
		SendTemplateValue value = getSendTemplate(serviceId);
		if (value == null && fun != null) {
			value = fun.apply(serviceId);
			if (value != null) {
				String key = getSendTemplateKey(serviceId);
				redisTemplate.set(key, value);
			}
		}
		return value;
	}
	
	@Override
	public void removeSendTemplate(String serviceId) {
		String key = getSendTemplateKey(serviceId);
		redisTemplate.delete(key);
	}

	@Override
	public void removeAllSendTemplate() {
		redisTemplate.deleteByMatches(RedisKeyConsts.SERVICE_SEND_TEMPLATE_KEY_PREFIX + "*");
	}

}
